import winreg
import time,os,threading

def check_registry_key(root_key, sub_key, value_name=None):
    """
    检查注册表键/值是否存在
    :param root_key: 根键 (如 winreg.HKEY_LOCAL_MACHINE)
    :param sub_key: 子键路径 (如 r"SOFTWARE\Microsoft\Windows\CurrentVersion")
    :param value_name: 要检查的值名称 (可选)
    :return: True/False 表示是否存在，None 表示权限不足
    """
    try:
        # 打开注册表键
        key = winreg.OpenKey(root_key, sub_key, 0, winreg.KEY_READ)
        
        # 如果指定了值名称，则检查该值
        if value_name:
            try:
                winreg.QueryValueEx(key, value_name)
                return True
            except FileNotFoundError:
                return False
        return True
    
    except FileNotFoundError:
        return False
    except PermissionError:
        return None
    finally:
        try:
            winreg.CloseKey(key)
        except:
            pass

def add_registry_key(root_key, sub_key, value_name=None, value_data="", value_type=winreg.REG_SZ):
    """
    添加或修改注册表键值
    :param root_key: 根键 (如 winreg.HKEY_LOCAL_MACHINE)
    :param sub_key: 子键路径 (如 r"SOFTWARE\MyApp")
    :param value_name: 值名称 (None 表示默认值)
    :param value_data: 值数据 (字符串/整数，根据类型匹配)
    :param value_type: 数据类型 (如 winreg.REG_SZ/REG_DWORD)
    :return: True 成功，False 失败
    """
    try:
        # 创建或打开键（自动递归创建父键）
        key = winreg.CreateKeyEx(root_key, sub_key, 0, winreg.KEY_WRITE)
        winreg.SetValueEx(key, value_name, 0, value_type, value_data)
        winreg.CloseKey(key)
        return True
    except PermissionError:
        print("错误：需要管理员权限")
    except Exception as e:
        print(f"操作失败：{str(e)}")
    return False

def delete_registry_value(root_key, sub_key, value_name):
    """
    删除注册表键值
    :param root_key: 根键 (如 winreg.HKEY_CURRENT_USER)
    :param sub_key: 子键路径 (如 r"SOFTWARE\MyApp")
    :param value_name: 要删除的值名称
    :return: True 成功，False 失败
    """
    try:
        # 打开注册表键（需写入权限）
        key = winreg.OpenKey(root_key, sub_key, 0, winreg.KEY_SET_VALUE)
        winreg.DeleteValue(key, value_name)
        winreg.CloseKey(key)
        return True
    except FileNotFoundError:
        print(f"错误：键值 '{value_name}' 不存在")
    except PermissionError:
        print("错误：需要管理员权限")
    except Exception as e:
        print(f"操作失败：{str(e)}")
    return False

def EnableChrome(path:str,isenabled:bool=True)->bool:
    ret=False
    if isenabled:
        if check_registry_key(winreg.HKEY_CURRENT_USER, path, "1"):
            ret=delete_registry_value(winreg.HKEY_CURRENT_USER, path, "1")
        ret=True
    else:
        if not check_registry_key(winreg.HKEY_CURRENT_USER, path, "1"):
            ret=add_registry_key(winreg.HKEY_CURRENT_USER, path,"1","chrome.exe")
        else: ret=True
    return ret


if __name__ == "__main__":
    # 示例：检查系统版本信息键值
    root = winreg.HKEY_LOCAL_MACHINE
    path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
    value = "ProductName"

    enable_time_rang=[9,19]

    #"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "DisallowRun" /t REG_DWORD /d 1 /f
    #"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun" /v "1" /t REG_SZ /d "chrome.exe" /f
    
    
    # while True:
    #     pass

    chromePath=r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun"

    # while True:
    now=time.localtime()
    hour=now.tm_hour
    min=now.tm_min
    print(hour,min)
    isenable = hour>=enable_time_rang[0] and hour<=enable_time_rang[1]
    action= 'enable' if isenable else 'disable'
    result=EnableChrome(chromePath, isenable)
    print(f'[{hour}:{min}]>>execute {action} {result}')
        # time.sleep(30)
    
    

